# coding: utf-8
import socket
import time

import paramiko
from host.extractor import extractor_disk, extractor_performance, extractor_status
from util.log import logger, logger_output
from util.store import SqlTool

# 采集项目
GATHER_CONFIG = {
    'disk': ('df -h|grep -v tmpfs|sed 1d', extractor_disk, 180),
    'process': ('ps -ef', None, 180),
    'network': ('netstat -antup', None, 180),
    'performance': ('top -b -n2', extractor_performance, 180)
}


def comunicate(ip, config):
    logger.info('主机交互:%s,%s' % (ip, config))
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    err_msg = ''
    key_file = config[3]
    # 2
    try:
        ssh.connect(
            hostname=ip,
            port=config[0],
            username=config[1],
            password=config[2],
            timeout=config[4],
            allow_agent=False,
            look_for_keys=True,
            key_filename=key_file
        )
    except paramiko.BadHostKeyException as e:
        err_msg += str(e)
    except paramiko.AuthenticationException as e:
        err_msg += str(e)
    except paramiko.SSHException as e:
        err_msg += str(e)
    except socket.error as e:
        err_msg += str(e)
    except Exception as e:
        err_msg += str(e)

    if err_msg:
        extractor_status(ip, str(err_msg))
        logger.error('登陆异常:%s,%s' % (ip, err_msg))
        return
    else:
        extractor_status(ip, 'success')

    # 3
    try:
        for t, cmd in GATHER_CONFIG.items():
            logger.info('信息收集:%s,%s,%s' % (ip, t, cmd))
            stdin, stdout, stderr = ssh.exec_command(cmd[0])
            content = stdout.read().decode()
            logger_output.info('%s,%s' % (ip, content))
            with SqlTool() as sql:
                sql.insert_primitive(ip, t, content, str(time.time()))
            if cmd[1]:
                cmd[1](ip, content, t)

    except AttributeError as e:
        logger.info('信息收集:%s,失败,%s' % (ip, e))
    except paramiko.SSHException as e:
        logger.info('信息收集:%s,失败,%s' % (ip, e))

    ssh.close()
    logger.info('交互完成:%s' % ip)
